package com.oocl.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oocl.pojo.Merchant;
import com.oocl.pojo.Protocol;
import com.oocl.pojo.State;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;
import com.oocl.util.DESUtil;
import com.oocl.util.JSONUtil;

@WebServlet("/approvalResult")
public class ApprovalResultServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantManager merchantManager;
	private Logger logger = Logger.getLogger(ApprovalResultServlet.class);
       
    public ApprovalResultServlet() {
        super();
        merchantManager = MerchantManagerFactory.getInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		String idSource = request.getParameter("id").replaceAll(" ", "+");
		DESUtil desUtil = new DESUtil();
		String id = desUtil.decrypt(idSource,"UTF-8");
		// check the status by id
		if(id != null){
			Merchant merchant = merchantManager.findMerchantById(id);
			int status=-1;
			if(merchant == null){
				status=-1;
			}else {
				status = merchant.getStatus();
			}
			
			State state = new State();
			state.setState(status);
			if(status==2){
				state.setContent(merchant.getbContent());
			}
			Protocol protocol = new Protocol(state);
			String json = JSONUtil.toJSON(protocol);
			writer.write(json);
			logger.info("respon status: "+status);
		} else {
			Protocol protocol = new Protocol(new String("Pls send the merchant id!"));
			String json = JSONUtil.toJSON(protocol);
			writer.write(json);
			logger.info("approval result without id");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
